import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import Axios from "axios";
import Api from "./api";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";

Vue.use(ElementUI);
Vue.config.productionTip = false;
Axios.defaults.baseURL = "http://172.16.6.125:8080";
Axios.defaults.timeout = 5000;
router.beforeEach(function (to, from, next) {
  if (to.name === 'Login') {
    next();
  } else {
    if (localStorage.getItem('isLogin')) {
      next();
    } else {
      next({
        path: '/login'
      })
    }
  }
});

const vm = new Vue({
    router,
    store,
    render: h => h(App)
}).$mount("#app");

Axios.interceptors.request.use(
    request => {
        vm.$store.dispatch("loadingStart"); // 显示loading组件
        request.headers["Content-Type"] = "application/json";
        if (localStorage.getItem("mtoken")) {
            request.headers["token"] = localStorage.getItem("mtoken");
        }
        return request;
    },
    error => {
        vm.$store.dispatch("loadingEnd");
        return Promise.reject(error);
    }
);

//4.2 添加响应拦截器
Axios.interceptors.response.use(
    response => {
        vm.$store.dispatch("loadingEnd");
        return response;
    },
    error => {
        vm.$store.dispatch("loadingEnd");
        return Promise.reject(error);
    }
);

Vue.prototype.$api = Api;
Vue.prototype.$axios = Axios;